<?php
use pft\Prod\Product;
use PFT\Db;
use PFT\SaleList;
include_once('common/autoload.php');
if(!$_SESSION['memberID']){exit("<script>window.location='dlogin.html'</script>");}
$dbConf = include './module/common/db.conf.php';
include '/module/common/Db.class.php';
Db::Conf($dbConf['localhost']);

$tpl    = Tpl::getLink();


$did         = intval($_POST["did"]);//分销商ID
$pri_list    = $_POST["pri_list"];//数组：pid=>价格
$pid_list    = $_POST["pid_list"]?$_POST["pid_list"]:array();//数组：pid=>lid
$bind   = intval($_POST["bind"]);//BOOL，是否套用了模板
$tplid  = intval($_POST["tplid"]);//模板id

$slo    = new SaleList(Db::Connect(), $_SESSION['sid'] ,$did);
//原先已经存在于evo表的pid，JSON
$pdata =  json_decode(base64_decode($_POST['pdata']), true);



if($bind && $tplid){
    if(($res=$tpl->apply($did, $tplid))===true){
        echo "<script>alert('配置成功')</script>";
    }
    else{
        echo "<script>alert('".$res."')</script>";
    }
}
else{
//    print_r($pid_list);exit;
    if(!$pri_list){
        exit("<script>alert('您并没有修改数据')</script>");
    }

//    print_r($pdata);
//    exit;
//    foreach($pid_list as $pid){
//        $_pri[$pid]=$pri_list[$pid];
//    }
//    $pids=array_unique(array_keys($_pri));

//    $pid_exist_list = $slo->getExistPid($did, $_SESSION['sid']);

    $price_pid   = array_keys($pri_list);
    //历史配置过的数据
    $exist_pid   = $slo->getExistPid($did, $_SESSION['sid']);
//    echo '$exist_pid';
//    print_r($exist_pid);
    //需要插入的数据
    $create_list     = array_diff($price_pid, $pdata);
    //需要将旧的状态更新为0
    $update_status_0 = array_intersect($create_list, $exist_pid);
    if (count($update_status_0)) {
        //新建的数据
        $create_list     = array_diff($create_list, $update_status_0);
    }
    //需要更新status为1（禁用）的数据
    $update_status_1 = array_diff($pdata, $price_pid);

    $msg = '';
    if (count($create_list)) {
        $ret_add = $slo->AddEvolute($create_list, $pid_list, $_SESSION['sid'], $did);
        $msg .= "新增数据{$ret_add}条" . '\n';
    }
    if (count($update_status_0)) {
        $ret_up_0 = $slo->UpdateEvoluteStatus($update_status_0, 0, $_SESSION['sid'], $did);
        $msg .= "更新状态为正常的数据{$ret_up_0}条" . '\n';
    }
    if (count($update_status_1)) {
        $ret_up_1 = $slo->UpdateEvoluteStatus($update_status_1, 1, $_SESSION['sid'], $did);
        $msg .= "更新状态为删除的数据{$ret_up_1}条" . '\n';
    }
    $upd="update uu_fx_tpl_cs set tplid=0 where fxid={$did} limit 1";
    $stmt = Db::Connect()->exec($upd);
//    print_r($pri_list);
//    exit;
    if(($res=$tpl->unusual($did,$pri_list))===true){
        echo "<script>alert('配置成功!{$msg}')</script>";
    }
    else{
        echo "<script>alert('".$res."')</script>";
    }
}
?>